<template>
  <common-list class="dataTypeDiv">
    <!-- <div class="app-container dataTypeDiv"> -->
    <el-row slot="tools" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['datascan:coredata:add']"
          >新增一级分类
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          v-hasPermi="['datascan:coredata:import']"
          icon="el-icon-download"
          @click="importShow"
          >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown @command="changeUserStatus">
          <el-button
            type="primary"
            plain
            icon="el-icon-upload2"
            :loading="exportLoading"
            class="btn-color-hover-white"
            v-hasPermi="['datascan:coredata:export']"
            >导出<commonIcon
              iconName="el-icon-arrow-down el-icon--right"
              iconType="icon"
              :iconSize="12"
              isStyle
            ></commonIcon>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="xlsx">XLSX</el-dropdown-item>
            <el-dropdown-item command="xls">XLS</el-dropdown-item>
            <el-dropdown-item command="html">HTML</el-dropdown-item>
            <el-dropdown-item command="xml">XML</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>

    <common-table
      slot="content"
      :data="typeList"
      isSetRowKey
      v-loading="loading"
      row-key="typeId"
      default-expand-all
      :tree-props="{ children: 'children' }"
    >
      <el-table-column label="代码" align="left" prop="typeCode" />
      <el-table-column label="类别名称" align="left" prop="typeName" />
      <el-table-column
        label="识别规则"
        align="left"
        prop="ruleNames"
        show-overflow-tooltip
      />
      <el-table-column
        label="备注"
        align="left"
        prop="remark"
        show-overflow-tooltip
      />
      <el-table-column label="操作" align="left" width="240px">
        <template slot-scope="scope">
          <el-button
            v-if="!scope.row.ruleIds && scope.row.typeLevel < '5'"
            type="text"
            @click="handleUpdate(scope.row, true)"
            v-hasPermi="['datascan:coredata:add']"
            >新增子分类 {{ scope.row.boundField }}
          </el-button>
          <el-button
            v-if="!scope.row.children"
            type="text"
            @click="handleBind(scope.row)"
            v-hasPermi="['datascan:coredata:relation']"
            >绑定识别规则
          </el-button>
          <el-button
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['datascan:coredata:edit']"
            >编辑
          </el-button>
          <el-button
            v-if="!scope.row.children"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['datascan:coredata:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <!-- 添加或编辑数据类别对话框 -->
    <common-edit-dialog
      :title="title"
      :visible.sync="open"
      :button-loading="submitLoading"
      @cancel="cancel"
      @submit="submitForm"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        @submit.native.prevent
      >
        <el-row :gutter="18">
          <el-col :span="24">
            <el-form-item v-if="addChild" label="类别名称" prop="typeCode">
              {{ typeCodeChild + "-" + typeNameChild }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="类别代码" prop="typeCode">
              <common-input
                v-model="form.typeCode"
                :verify="false"
                :maxlength="16"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="类别名称" prop="typeName">
              <common-input
                v-model="form.typeName"
                placeholder="请输入"
                :maxlength="16"
                :disabled="this.form.typeId != null"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-show="false" label="父类id" prop="parentTypeId">
              <common-input v-model="form.parentTypeId" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-show="false" label="层级" prop="typeLevel">
              <common-input v-model="form.typeLevel" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <common-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </common-edit-dialog>
    <Ruledialog ref="ruleDialog" @submitbindForm="submitbindForm"></Ruledialog>

    <common-upload-dialog
      download-path="/system/b/coredata/exportData"
      upload-path="/system/b/coredata/importData"
      template-name="coredataType.xlsx"
      report-path="/system/downErrorReportByemplateName"
      ref="uploadDialog"
      :getList="getList"
    />
  </common-list>
</template>

<script>
import BaseList from "@/mixins/BaseList";
import {
  queryTreeList,
  queryAdd,
  queryUpdate,
  queryDelete,
  query,
  discernRuleList,
  deleteCheck,
} from "@/api/datascan/coredata";
import Ruledialog from "./components/ruleDialog";
import CommonIcon from "@/components/CommonIcon";
export default {
  name: "coredata",
  components: { Ruledialog, CommonIcon },
  mixins: [BaseList],
  data() {
    return {
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示查询条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据类别表格数据
      typeList: [],
      addChild: false, // 新增子集弹框
      typeCodeChild: null,
      typeNameChild: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      bindTitle: "",
      bindOpen: false,
      bindCheckList: [],
      bindCheckAll: [],
      // 查询参数
      queryParams: {
        pageNum: 0,
        pageSize: 10,
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        typeCode: [
          {
            required: true,
            message: "请输入类别代码",
            trigger: "blur",
          },
          // {
          //   min: 2,
          //   max: 30,
          //   message: "长度在 2 到 30 个字符",
          //   trigger: "blur",
          // },
        ],
        remark: [{ max: 256, message: "长度不能超过256", trigger: "blur" }],
        typeName: [
          { required: true, message: "请输入类别名称", trigger: "blur" },
        ],
        // remark: [{ max: 140, message: '长度不能超过140', trigger: 'blur' }]
      },
      submitLoading: false,
      fieldSubmitLoading: false,
      key: "typeId",
      exportLoading: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    changeUserStatus(data) {
      this.exportLoading = true;
      this.download(
        "/system/b/coredata/exportForm",
        {
          ...this.queryParams,
          pageSize: 10000,
          exportType: data,
        },
        `核心数据分类${new Date().getTime()}.${data}`,
        1800000
      ).finally(() => {
        this.exportLoading = false;
      });
    },
    handleBind(row) {
      this.$refs.ruleDialog.show(row);
    },
    /** 查询数据类别列表 */
    getList() {
      this.loading = true;
      queryTreeList(this.queryParams)
        .then((res) => {
          if (res && res.code === 200) {
            this.typeList = res.data;
          } else {
            this.typeList = [];
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //导入
    importShow() {
      this.$refs.uploadDialog.show();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.resetChild();
    },

    // 表单重置
    reset() {
      this.form = {
        typeId: undefined,
        typeCode: undefined,
        typeName: undefined,
        parentTypeId: "0",
        typeLevel: "1",
        createTime: undefined,
        updateTime: undefined,
        remark: undefined,
        delFlag: undefined,
      };
      this.resetForm("form");
    },
    resetChild() {
      this.addChild = false;
      this.typeCodeChild = null;
      this.typeNameChild = null;
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.typeId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.resetChild();
      this.open = true;
      this.title = "新增一级分类";
    },
    /** 编辑按钮操作 */
    handleUpdate(row, flag) {
      if (flag) {
        this.addChild = true;
        this.title = "新增子分类";
      } else {
        this.title = "编辑分类";
      }
      this.reset();
      this.resetChild();
      const typeId = row.typeId || this.ids;
      query({ typeId })
        .then((res) => {
          if (res && res.code === 200) {
            if (flag) {
              this.typeCodeChild = res.data.typeCode;
              this.typeNameChild = res.data.typeName;
              this.form = Object.assign({}, res.data, {
                typeId: undefined,
                typeCode: undefined,
                typeName: undefined,
                parentTypeId: res.data.typeId,
                typeLevel: undefined,
                createTime: undefined,
                updateTime: undefined,
                remark: undefined,
                delFlag: undefined,
              });
            } else {
              this.form = Object.assign({}, res.data, {
                parentTypeId: undefined,
                typeLevel: undefined,
                createTime: undefined,
                updateTime: undefined,
                delFlag: undefined,
              });
            }
          } else {
            this.$GlobalErrorConfirm("数据加载失败", res.msg);
          }
        })
        .finally(() => {
          this.open = true;
        });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          if (this.form.typeId != null) {
            queryUpdate(this.form)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("编辑成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("编辑失败", res.msg);
                }
              })
              .finally(() => (this.submitLoading = false));
          } else {
            queryAdd(this.form)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg);
                }
              })
              .finally(() => (this.submitLoading = false));
          }
        }
      });
    },
    /** 删除按钮操作 */
    deleteData(row) {
      const typeId = row?.typeId || this.ids;
      this.$GlobalDeleteConfirm()
        .then(() => {
          queryDelete({ typeId }).then((res) => {
            if (res && res.code === 200) {
              this.queryParams.pageNum = 1;
              this.getList();
              this.$GlobalSuccessMessage("删除成功");
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },
    /**  删除前校验 */
    beforeDeleteForCheck(ids) {
      return new Promise((resolve, reject) => {
        deleteCheck({ typeId: ids })
          .then((res) => {
            if (res && res.code === 200) {
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    submitbindForm(params) {
      discernRuleList(params)
        .then((res) => {
          if (res && res.code === 200) {
            this.$GlobalSuccessMessage("绑定成功");
            this.$refs.ruleDialog.bindCancel();
            this.getList();
            this.bindOpen = false;
          } else {
            this.$GlobalErrorConfirm("绑定失败", res.msg);
          }
        })
        .finally(() => this.$refs.ruleDialog.closeLoading());
    },
  },
};
</script>

<style lang="scss">
.dataTypeDiv {
  .el-table__indent {
    padding-left: 50px !important;
  }
}
</style>
